package com.chuang.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuang.server.config.security.JwtTokenUtil;
import com.chuang.server.mapper.UserMapper;
import com.chuang.server.pojo.ResultBean;
import com.chuang.server.pojo.ResultPageBean;
import com.chuang.server.pojo.User;
import com.chuang.server.pojo.UserLoginParams;
import com.chuang.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

import static com.chuang.server.util.GetSysTime.getTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2021-12-14
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public List<Map<Object,Object>> selectAll(){
        return userMapper.selectAll();
    }

    @Override
    public Map<Object,Object> selectUserById(int id) {

        return userMapper.selectUserById(id);
    }

    @Override
    public int addUser(User user) {

        return userMapper.addUser(user);
    }

    @Override
    public int delUserById(int id) {
       return  userMapper.deleteById(id);
    }

    @Override
    public ResultBean login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        log.info("ceshi");
        if (null == userDetails ) {
            return ResultBean.error("用户名或密码不正确");
        }
        if(!userDetails.getUsername().equals(username)||!userDetails.getPassword().equals(password)){
            return ResultBean.error("用户名或密码不正确");
        }
        // 更新security 用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",tokenHead+ ' ' +token);

        return ResultBean.success("登录成功",tokenMap);
    }

    @Override
    public ResultBean register(JSONObject jsonObject) {
        String name = jsonObject.getString("name");
        String LoginName = jsonObject.getString("LoginName");
        String LoginPassword = jsonObject.getString("LoginPassword");
        Long quota = jsonObject.getLong("quota");
        String resetPassword = jsonObject.getString("resetPassword");
        if(!LoginPassword.equals(resetPassword)){
            return ResultBean.error("密码输入不一致");
        }
        User user = userMapper.selectUserByName(LoginName);
        if(user != null){
            return ResultBean.error("该用户名已经被注册过");
        }

        int register = userMapper.register(name,LoginName,LoginPassword,quota);
        if(register>0){
            return ResultBean.success("注册成功");
        }
        return ResultBean.error("注册失败");

    }

    @Override
    public User getUserByName(String name) {
        return userMapper.selectUserByName(name);
    }

    public ResultPageBean selectUserPage(Page<User> page, Integer state) {
        IPage<User> userIPage = userMapper.selectPageVo(page, state);
        return ResultPageBean.success("成功",userIPage.getRecords(),userIPage.getTotal(),userIPage.getSize(),userIPage.getCurrent(),userIPage.getPages());
    }

}
